package example;


import com.ctg.faas.runtime.*;
import example.util.ServletUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class StreamHandler implements StreamRequestHandler, FunctionInitializer, PreStopHandler {

    @Override
    public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
        FunctionComputeLogger logger = context.getLogger();
        context.getLogger().info("StreamRequestHandler hello");
        logger.info("StreamRequestHandler loger hello");

        String inStr = ServletUtil.getInputString(input);
        context.getLogger().info("input :"+inStr);
        String req = String.format("input: %s\n", inStr);

        output.write(req.getBytes());
        output.flush();
        output.close();
    }

    /**
     * 做一些实例初始化的工作，比如初始化
     * @param context The function compute initialize environment context object.
     * @throws IOException
     */
    @Override
    public void initialize(Context context) throws IOException {
        context.getLogger().info("init");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        context.getLogger().info("init ok");
    }

    /**
     * 实例关停
     * @param context The function compute preStop environment context object.
     * @throws IOException
     */
    @Override
    public void preStop(Context context) throws IOException {
        context.getLogger().info("stop");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        context.getLogger().info("stop ok");
    }
}